package com.rm.zeyou.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.rm.zeyou.entity.Merchant;
import com.rm.zeyou.entity.Technician;
import com.rm.zeyou.entity.UserAttention;
import com.rm.zeyou.mapper.MerchantMapper;
import com.rm.zeyou.mapper.TechnicianMapper;
import com.rm.zeyou.mapper.UserAttentionMapper;
import com.rm.zeyou.response.ApiRestResponse;
import com.rm.zeyou.service.TechnicianService;
import com.rm.zeyou.service.UserAttentionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rm.zeyou.util.check.CheckEmptyUtil;
import com.rm.zeyou.util.distance.MathDistanceUtil;
import com.rm.zeyou.vo.request.AttentionRequestVo;
import com.rm.zeyou.vo.response.SelectAttentionResponseVo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 关注表 服务实现类
 * </p>
 *
 * @author YanYang
 * @since 2025-03-12 15:55:09
 */
@Service
public class UserAttentionServiceImpl extends ServiceImpl<UserAttentionMapper, UserAttention> implements UserAttentionService {
    @Resource
    private UserAttentionMapper userAttentionMapper;
    @Resource
    private TechnicianMapper technicianMapper;
    @Resource
    private MerchantMapper merchantMapper;
    @Resource
    private TechnicianService technicianService;

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public ApiRestResponse<Integer> attention(Long userId, AttentionRequestVo requestVo) {
        UserAttention userAttention = userAttentionMapper.selectOne(new LambdaQueryWrapper<UserAttention>()
                .eq(UserAttention::getUserId, userId)
                .eq(UserAttention::getTid, requestVo.getTid()));
        Integer result;
        if (!CheckEmptyUtil.isEmpty(userAttention)) {
            //已关注 取消
            result = userAttentionMapper.cancelAttention(userId, requestVo.getTid());
        } else {
            //未关注 关注
            UserAttention insertAttention = new UserAttention();
            insertAttention.setTid(requestVo.getTid());
            insertAttention.setUserId(userId);
            result = userAttentionMapper.insert(insertAttention);
        }
        return ApiRestResponse.success(result);
    }

    @Override
    public ApiRestResponse<PageInfo<SelectAttentionResponseVo>> selectAttentionList(Long userId, AttentionRequestVo requestVo) {
        PageHelper.startPage(requestVo.getPageNum(), requestVo.getPageSize());
        List<UserAttention> attentions = userAttentionMapper.selectList(new LambdaQueryWrapper<UserAttention>()
                .eq(UserAttention::getUserId, userId));
        if (CheckEmptyUtil.isEmpty(attentions)) {
            return ApiRestResponse.success(new PageInfo<SelectAttentionResponseVo>());
        }

        PageInfo<UserAttention> source = new PageInfo<>(attentions);
        PageInfo<SelectAttentionResponseVo> target = new PageInfo<>();
        BeanUtils.copyProperties(source, target);
        List<UserAttention> list = source.getList();
        List<Long> tidList = list.stream().map(UserAttention::getTid).collect(Collectors.toList());
        List<Technician> technicianList = technicianMapper.selectList(new LambdaQueryWrapper<Technician>()
                .in(Technician::getId, tidList));
        Map<Long, Technician> technicianMap = technicianList.stream().collect(Collectors.toMap(Technician::getId, Function.identity()));

        List<SelectAttentionResponseVo> voList = new ArrayList<>();
        for (UserAttention userAttention : list) {
            SelectAttentionResponseVo vo = new SelectAttentionResponseVo();
            Merchant merchant = merchantMapper.selectById(userAttention.getTid());
            vo.setMerchantName(!CheckEmptyUtil.isEmpty(merchant) ? merchant.getMerchantName() : "");
            Integer orderReceiving = technicianService.selectTechnicianOrderReceiving(technicianMap.get(userAttention.getTid()));
            vo.setTid(technicianMap.get(userAttention.getTid()).getId());
            vo.setTechnicianName(technicianMap.get(userAttention.getTid()).getTechnicianName());
            vo.setOrderReceiving(orderReceiving+technicianMap.get(userAttention.getTid()).getOrderReceiving());
            vo.setTechnicianAvatar(technicianMap.get(userAttention.getTid()).getTechnicianAvatar());
            vo.setMark(technicianMap.get(userAttention.getTid()).getMark());

            String distance = MathDistanceUtil.getDistance(requestVo.getLongitude() + "," + requestVo.getLatitude(),
                    technicianMap.get(userAttention.getTid()).getLongitude() + "," + technicianMap.get(userAttention.getTid()).getLatitude(),
                    2);
            BigDecimal distanceBig = new BigDecimal(distance).divide(new BigDecimal(1000), 2, RoundingMode.HALF_UP);
            vo.setDistance(distanceBig.toPlainString());
            voList.add(vo);
        }
        target.setList(voList);

        return ApiRestResponse.success(target);
    }
}
